package com.ruoyi.web.cp.service.rm;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.web.core.config.ConfigLoader;
import com.ruoyi.web.cp.domain.rm.RmResult;
import com.ruoyi.web.cp.domain.rm.RmobDx2Merge;
import com.ruoyi.web.cp.service.WinxinService;
import com.ruoyi.web.mapper.RmResultMapper;
import com.ruoyi.web.mapper.RmobDx2MergeMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RmResultDx2MergeService {
    @Autowired
    private RmobDx2MergeMapper rmobDx2MergeMapper;
    @Autowired
    private RmResultMapper rmResultMapper;
    @Autowired
    private WinxinService winxinService;
    @Autowired
    private ConfigLoader configLoader;

    @SneakyThrows
    public void merge(Date beginDate, Date endDate) {
        beginDate = DateUtil.offsetHour(new Date(), -24);
        List<RmobDx2Merge> rmobDyMergeList = getRmobDyMergeList(beginDate, null);
        if (CollUtil.isEmpty(rmobDyMergeList)) {
            return;
        }
        List<String> gameIds = rmobDyMergeList.stream().map(RmobDx2Merge::getGameId)
                .distinct()
                .collect(Collectors.toList());
        List<RmResult> rmResultList = getResultsByGameIds(gameIds);
        // 生成 gameId -> allScore 的字典
        Map<String, RmResult> gameIdToAllScoreMap = rmResultList.stream()
                .collect(Collectors.toMap(
                        RmResult::getGameId,
                        v -> v,
                        (existing, replacement) -> existing
                ));

        // 后续可以使用该字典进行匹配、更新等操作
        // 例如：遍历 rmobDyMergeList 并关联 allScore
        for (RmobDx2Merge merge : rmobDyMergeList) {
            RmResult rmResult = gameIdToAllScoreMap.get(merge.getGameId());
            if (rmResult != null) {
                merge.setRmResult(rmResult);
            }
        }

        String path = configLoader.getRmPath() + "小2首5结果.xlsx";
        File tempFile = new File(path);
        // 如果文件已存在，先删除
        if (tempFile.exists()) {
            FileUtil.del(tempFile);
        }
        // 导出到 Excel
        exportRmobDyMergeToExcel(rmobDyMergeList, tempFile);
        winxinService.uploadMediaByAppAndSendMsg("1000003", path);
    }

    public List<RmobDx2Merge> getRmobDyMergeList(Date beginDate, Date endDate) {
        return rmobDx2MergeMapper.selectByDateBetween(beginDate, endDate);
    }

    public List<RmResult> getResultsByGameIds(List<String> gameIds) {
        return rmResultMapper.selectByGameIds(gameIds);
    }

    public void exportRmobDyMergeToExcel(List<RmobDx2Merge> rmobDyMergeList, File tempFile) {
        // 创建 ExcelWriter 对象
        ExcelWriter writer = ExcelUtil.getWriter(tempFile);

        // 手动设置表头
        String[] headers = {"日期", "联赛", "主队", "客队", "RM赔率", "大小球", "OB独平赔率", "首进球时间", "半场结果", "全场结果", "红黑"};
        writer.writeHeadRow(Arrays.asList(headers));

        // 写入数据（假设 RmobDyMerge 有对应的 getter 方法）
        for (RmobDx2Merge item : rmobDyMergeList) {
            if (item.getDetailsJson() == null) {
                continue;
            }
            Date date = item.getDate();
            JSONObject detail = item.getDetailsArray().getJSONObject(0);

            String dateStr = DateUtil.format(date, "yyyy-MM-dd HH:mm");
            String redBlack = "";
            RmResult rmResult = item.getRmResult();
            String goalTime = "", halfScore = "", allScore = "";
            if (rmResult != null) {
                goalTime = rmResult.getGoalTime() == null ? "" : rmResult.getGoalTime();
                if (goalTime.length() > 2) {
                    if (goalTime.contains("终场")) {
                        redBlack = "红";
                    } else {
                        redBlack = Integer.parseInt(goalTime.substring(0, 2)) < 6 ? "黑" : "红";
                    }
                }
                halfScore = rmResult.getHalfScore() == null ? "" : rmResult.getHalfScore();
                allScore = rmResult.getAllScore() == null ? "" : rmResult.getAllScore();
            }
            writer.writeRow(Arrays.asList(
                    dateStr,            // 日期
                    item.getLeague(),          // 联赛
                    item.getTeamA(),           // 主队
                    item.getTeamB(),           // 客队
                    detail.getString("rm_plv"),          // RM赔率
                    detail.getString("ob_goalDesc"),          // OB大小球
                    detail.getString("ob_plv"),    // OB独平赔率
                    goalTime,           // 首进球时间
                    halfScore,          // 半场结果
                    allScore,          // 全场结果
                    redBlack            // 红黑
            ));
        }
        int[] columnWidths = {
                18 * 256, // 日期
                15 * 256, // 联赛
                20 * 256, // 主队
                20 * 256, // 客队
                10 * 256, // RM赔率
                12 * 256, // OB独平赔率
                12 * 256, // OB大小球
                15 * 256,   // 首进球时间
                8 * 256,   // 半场结果
                8 * 256,  // 全场结果
                6 * 256   // 红黑
        };

        for (int i = 0; i < columnWidths.length; i++) {
            writer.getSheet().setColumnWidth(i, columnWidths[i]);
        }
        // 关闭流
        writer.close();
    }

}
